<template>
  <!-- 客户列表 -->
  <div class="mod-user">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
      >
        <div class="input-row">
          <el-form-item
            prop="nickName"
            :label="$t('users.name') + ':'"
          >
            <el-input
              v-model="searchForm.nickName"
              type="text"
              clearable
              :placeholder="$t('users.name')"
            />
          </el-form-item>
          <el-form-item
            prop="userMobile"
            :label="$t('publics.mobilePhone') + ':'"
          >
            <el-input
              v-model="searchForm.userMobile"
              type="text"
              clearable
              :placeholder="$t('publics.mobilePhone')"
            />
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="resetForm()"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('admin:coupon:send')"
          class="default-btn"
          :class="{'disabled-btn': dataListSelections.length <= 0}"
          @click="updateCoupon()"
        >
          {{ $t('user.sendCoupons') }}
        </div>
        <div
          v-if="isAuth('user:clientList:addLabel')"
          class="default-btn"
          :class="{'disabled-btn': dataListSelections.length <= 0}"
          @click="updateTags()"
        >
          {{ $t('user.tagging') }}
        </div>
        <div
          v-if="isAuth('customer:customerList:importCustomer')"
          class="primary-btn default-btn"
          :disabled="importDisabled"
          @click="importUser()"
        >
          {{ $t('user.clientImport') }}
        </div>
        <div
          v-if="isAuth('customer:customerList:exportCustomer')"
          class="primary-btn default-btn"
          :disabled="exportDisabled"
          @click="exportUser()"
        >
          {{ $t('user.clientExport') }}
        </div>
      </div>
      <div class="table-con">
        <div
          v-if="dataList.length === 0"
          class="empty-text"
        >
          {{ $t('user.noData') }}
        </div>
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            align="center"
            width="60"
          />
          <el-table-column
            :label="$t('users.name')"
            prop="nickName"
            align="center"
          />
          <el-table-column
            prop="pic"
            :label="$t('publics.profilePicture')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <img
                  v-if="!scope.row.pic"
                  src="@/assets/img/userImg.jpg"
                  style="width: 130px;"
                  alt
                >
                <img
                  v-else
                  :src="checkFileUrl(scope.row.pic)"
                  alt
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="userMobile"
            align="center"
            :label="$t('publics.mobilePhone')"
          />
          <el-table-column
            align="center"
            prop="totalOrderTimes"
            width="120"
            :label="$t('user.totalOrderTimes')"
            sortable
          />
          <el-table-column
            align="center"
            prop="consTimes"
            width="120"
            :label="$t('user.consumptionTimes')"
            sortable
          />
          <el-table-column
            width="120"
            prop="consAmount"
            :label="$t('user.consumptionAmount')"
            sortable
          >
            <template #default="scope">
              <div>{{ scope.row.consAmount || 0 }}</div>
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            prop="actualAmount"
            :label="$t('user.actuallypaid')"
            sortable
          >
            <template #default="scope">
              <div>{{ scope.row.actualAmount || 0 }}</div>
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            prop="averDiscount"
            :label="$t('user.averageDiscount')"
            sortable
          />
          <el-table-column
            align="center"
            width="120"
            prop="afterSaleTimes"
            :label="$t('user.refundTimes')"
            sortable
          />
          <el-table-column
            width="150"
            prop="afterSaleAmount"
            :label="$t('home.refundAmount')"
            sortable
          />
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('customer:customerList:edit')"
                  class="text-btn default-btn"
                  @click.stop="onAddOrUpdate(scope.row.userId)"
                >
                  {{ $t('user.edit') }}
                </div>
              </div>
            </template>
          </el-table-column>

          <template #empty>
            <div>
                &nbsp;
            </div>
          </template>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <update-growth
      v-if="updateGrowthVisible"
      ref="updateGrowthRef"
      @refresh-data-list="refreshChange"
    />
    <update-customer-coupon
      v-if="updateCouponVisible"
      ref="updateCouponRef"
      :get-way="1"
      @refresh-data-list="refreshChange"
    />
    <excel-customer-import
      v-if="importUserVisible"
      ref="importUserRef"
      :type="0"
      @refresh-data-list="refreshChange"
    />

    <tags-select
      v-if="tagsSelectVisible"
      ref="tagsSelectRef"
      :tag-category="0"
      :limit="5"
      @refresh-tags-arr="refreshTagsSelect"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import UpdateCustomerCoupon from './components/update-customer-coupon/index.vue'
import ExcelCustomerImport from './components/excel-customer-import/index.vue'
import { ElLoading } from 'element-plus'
import { isAuth, checkFileUrl } from '@/utils/index.js'

const importDisabled = ref(false)
const tagsSelectVisible = ref(false)

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const searchForm = reactive({
  nickName: '',
  userMobile: '',
  isMember: ''
})

onMounted(() => {
  getDataList(page)
})

const dataList = ref([])
let tempSearchForm = null // 保存上次点击查询的请求条件
// 获取客户列表  /user/user/pageCustomer
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/user/user/pageCustomer'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
// 新增 / 修改
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, 0)
  })
}

let dynamicTags = []
// 条件查询 JSON.stringify(arr)
const onSearch = (newData = false) => {
  let arr = ''
  dynamicTags.forEach(item => {
    if (item.userTagId === dynamicTags[dynamicTags.length - 1].userTagId) {
      arr = arr + item.userTagId
      return
    }
    arr = arr + item.userTagId + ','
  })
  searchForm.customerTagIds = arr
  page.currentPage = 1
  getDataList(page, newData)
}

// 刷新回调用
const refreshChange = () => {
  getDataList(page)
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}

const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}

const searchFormRef = ref(null)
const resetForm = () => {
  searchFormRef.value.resetFields()
  clearAllTags()
}

const dataListSelections = ref([])
// 多选变化
const selectionChange = (val) => {
  dataListSelections.value = val
}

const updateGrowthVisible = ref(false)
const updateGrowthRef = ref(null)
// 修改成长值
const updateGrowth = (id) => {
  if (dataListSelections.value.length <= 0) {
    return
  }
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateGrowthVisible.value = true
  nextTick(() => {
    updateGrowthRef.value?.init(ids)
  })
}

const updateTags = () => {}

const updateCouponVisible = ref(false)
const updateCouponRef = ref(null)
const updateCoupon = (id) => {
  if (dataListSelections.value.length <= 0) {
    return
  }
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateCouponVisible.value = true
  nextTick(() => {
    updateCouponRef.value?.init(ids)
  })
}

// 清除所有标签
const clearAllTags = () => {
  dynamicTags = []
}
// 选择到的标签tagId
const refreshTagsSelect = (data) => {
  clearAllTags()
  dynamicTags = data
}

const importUserVisible = ref(false)
const importUserRef = ref(null)
/**
 * 导入用户
 */
const importUser = () => {
  importUserVisible.value = true
  nextTick(() => {
    importUserRef.value?.init()
  })
}

const exportDisabled = ref(false)
/**
 * 导出客户
 */
const exportUser = () => {
  exportDisabled.value = true
  const loading = ElLoading.service({
    lock: true,
    target: '.table-con',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('formData.exportIng')
  })
  http({
    url: http.adornUrl('/user/user/exportCustomer'),
    method: 'get',
    params: http.adornParams(searchForm),
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    loading.close()
    exportDisabled.value = false
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('user.clientInformationForm')
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch((e) => {
    loading.close()
  })
}

</script>
<style lang="scss" scoped>
@use "index";
</style>
